<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();
import { Rules, addRules, updateRules, deleteManage } from '@/utils/api';
import { ElMessage, ElMessageBox } from 'element-plus'
let areaId = null;
let iau = true;
let uId = '';
const isadd = ref(false);
const rules = ref([]);
const pageNum = ref(1);
const currentPage = ref(1);
const totalElements = ref(0);
const ruleFormRef = ref(null);
const ruleForm = ref({
    ruleName: '',
    date: '',
    workdayOpenTime: '',
    workdayCloseTime: '',
    weekendOpenTime: '',
    weekendCloseTime: '',
    maxNum: 20000
})


const godetails = (data) => {
    router.push({ path: '/enterGarden/details', query: { id: data.id } })
}

const openadd = () => {
    iau = true;
    for (let key in ruleForm.value) {
        ruleForm.value[key] = '';
    }
    ruleForm.value.maxNum = 20000;
    isadd.value = true;
}

const rule = reactive({
    ruleName: [
        { required: true, message: '请输入规则名称', trigger: 'blur' },
        { min: 2, max: 6, message: '名称长度在2~6之间', trigger: 'blur' }
    ],
    date: [
        {
            type: 'daterange',
            required: true,
            message: '请选择日期范围',
            trigger: 'change',
        },
    ],
    workdayOpenTime: [
        {

            required: true,
            message: '请选择开始时间',
            trigger: 'change',
        },
    ],
    workdayCloseTime: [
        {
            required: true,
            message: '请选择结束时间',
            trigger: 'change',
        },
    ],
    weekendOpenTime: [
        {
            required: true,
            message: '请选择开始时间',
            trigger: 'change',
        },
    ],
    weekendCloseTime: [
        {
            required: true,
            message: '请选择结束时间',
            trigger: 'change',
        },
    ],
    maxNum: [
        { required: true, message: '请输入入园人数限制', trigger: 'blur' }
    ]
})

const formatProcessingTime = (data) => {
    if (data != null && data != '') {
        let datetime = new Date(data[0]);
        let year = datetime.getFullYear();
        let month = datetime.getMonth() + 1;
        let date = datetime.getDate();

        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }
        let datetime2 = new Date(data[1]);
        let year2 = datetime2.getFullYear();
        let month2 = datetime2.getMonth() + 1;
        let date2 = datetime2.getDate();

        if (month2 >= 1 && month2 <= 9) {
            month2 = "0" + month2;
        }
        if (date2 >= 0 && date2 <= 9) {
            date2 = "0" + date2;
        }

        return year + "-" + month + "-" + date + "~" + year2 + "-" + month2 + "-" + date2;
    } else {
        return ""
    }
}

const delItem = function (data) {
    ElMessageBox.confirm(
        '是否要永久删除该数据. 继续?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deleteManage(data.id).then(res => {
                if (res.code == '200') {
                    resetData();
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.message,
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
};

const openmf = function (data) {
    iau = false;
    let Obj = Object.assign({}, data);
    Obj.date = [new Date(Obj.startDate), new Date(Obj.endDate)]
    uId = Obj.id;
    ruleForm.value = Object.assign({}, Obj);
    isadd.value = true;
};

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const pm = ruleForm.value;
            let params = {
                "areaId": areaId,
                "ruleName": pm.ruleName,
                "startDate": formatProcessingTime(pm.date).split('~')[0],
                "endDate": formatProcessingTime(pm.date).split('~')[1],
                "workdayOpenTime": pm.workdayOpenTime,
                "workdayCloseTime": pm.workdayCloseTime,
                "weekendOpenTime": pm.weekendOpenTime,
                "weekendCloseTime": pm.weekendCloseTime,
                "maxNum": pm.maxNum
            }
            if (iau) {
                addRules(params).then(res => {
                    if (res.code == '200') {
                        ElMessage({
                            message: '设置规则成功',
                            type: 'success',
                        })
                        resetData();
                        isadd.value = false;
                    } else {
                        ElMessage({
                            message: res.message,
                            type: 'warning',
                        })
                    }
                })
            } else {
                params['id'] = uId;
                updateRules(params).then(res => {
                    if (res.code == '200') {
                        ElMessage({
                            message: '设置规则成功',
                            type: 'success',
                        })
                        resetData();
                        isadd.value = false;
                    } else {
                        ElMessage({
                            message: res.message,
                            type: 'warning',
                        })
                    }
                })
            }


        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
    isadd.value = false;
}

const getRules = async () => {
    let params = '?areaId=' + areaId + '&pageNum=' + pageNum.value + '&pageSize=15'
    let res = await Rules(params)
    if (res.code == '200') {
        rules.value = res.data.content;
        totalElements.value = res.data.totalElements;
    }
}

const handleSizeChange = (val) => {
    pageNum.value = val;
    getRules();
};

const resetData = () => {
    pageNum.value = 1;
    currentPage.value = 1;
    getRules();
}

onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');
    getRules();
})

</script>
<template>
    <div class="wls-aut">
        <div class="wls-aut-title" style="justify-content: space-between;">
            <div style="font-weight: 700;"><span>入园管理</span></div>
        </div>
        <div class="wls-aut-container" style="padding: .24rem;">
            <el-row>
                <el-col :span="24" style="text-align: right;">
                    <el-button type="primary" @click.stop="openadd">设置规则</el-button>
                </el-col>
            </el-row>

            <ul class="rule-box">
                <li class="rule-box-li" v-for="(i, index) in rules">
                    <div class="rule-title">
                        <span>{{ i.ruleName }}</span>
                    </div>
                    <div class="rule-text">
                        <span>日期范围</span>
                        <span>{{ i.startDate }}至{{ i.endDate }}</span>
                    </div>
                    <div class="rule-text">
                        <span>周一至周五</span>
                        <span>{{ i.workdayOpenTime }}至{{ i.workdayCloseTime }}</span>
                    </div>
                    <div class="rule-text">
                        <span>周末</span>
                        <span>{{ i.weekendOpenTime }}至{{ i.weekendCloseTime }}</span>
                    </div>
                    <div class="rule-text">
                        <span>入园人数限制</span>
                        <span>{{ i.maxNum }}</span>
                    </div>
                    <div class="rule-btn-box">
                        <div @click.stop="godetails(i)"><span>详情</span></div>
                        <div @click.stop="openmf(i)"><span>修改</span></div>
                        <div @click.stop="delItem(i)"><span>删除</span></div>
                    </div>
                </li>
            </ul>

            <el-pagination v-model:current-page="currentPage" :page-size="15" :pager-count="5" :small="true"
                :disabled="false" background layout="total, prev, pager, next, jumper" :total="totalElements"
                @current-change="handleSizeChange" />
        </div>

        <div class="hsq-popup" v-if="isadd">
            <div class="rule-form">
                <div class="hsq-popup-title">
                    <div class="hsq-popup-shu "></div>
                    <span>入园规则</span>
                </div>

                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rule" class="demo-ruleForm" label-position="top"
                    size="large" status-icon>
                    <el-form-item label="规则名称" prop="ruleName">
                        <el-input v-model="ruleForm.ruleName" maxlength="6" minlength="2" style="width: 100%;" />
                    </el-form-item>
                    <el-form-item label="日期范围" prop="date">
                        <el-date-picker v-model="ruleForm.date" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" />
                    </el-form-item>
                    <div class="rules-title">
                        <span>周一至周五</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="开始时间" prop="workdayOpenTime">
                                <el-time-select v-model="ruleForm.workdayOpenTime" :max-time="ruleForm.workdayCloseTime"
                                    class="mr-4" placeholder="开始时间" start="06:00" step="00:30" end="22:30" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="结束时间" prop="workdayCloseTime">
                                <el-time-select v-model="ruleForm.workdayCloseTime" :min-time="ruleForm.workdayOpenTime"
                                    placeholder="结束时间" start="06:00" step="00:30" end="22:30" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div class="rules-title">
                        <span>周末</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="开始时间" prop="weekendOpenTime">
                                <el-time-select v-model="ruleForm.weekendOpenTime" :max-time="ruleForm.weekendCloseTime"
                                    class="mr-4" placeholder="开始时间" start="06:00" step="00:30" end="22:30" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="结束时间" prop="weekendCloseTime">
                                <el-time-select v-model="ruleForm.weekendCloseTime" :min-time="ruleForm.weekendOpenTime"
                                    placeholder="结束时间" start="06:00" step="00:30" end="22:30" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="入园人数限制" prop="maxNum">
                        <el-input-number v-model="ruleForm.maxNum" style="width: 100%;" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>

            </div>
        </div>
    </div>
</template>
<style scoped>
.rule-box {
    width: 100%;
    padding: 1px;
    overflow: hidden;
}

.rule-box-li {
    float: left;
    width: calc((100% - 1rem) / 5);
    margin-right: 0.24rem;
    margin-top: .24rem;
    border-radius: 4px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.2);
    cursor: pointer;
    overflow: hidden;
}

.rule-box-li:nth-child(5n) {
    margin-right: 0;
}

.rule-title {
    font-weight: 700;
    padding: 0.16rem;
}

.rules-title {
    font-weight: 700;
    margin-bottom: 0.16rem;
}

.rule-text {
    width: 100%;
    height: 0.3rem;
    padding: 0.16rem;
    color: #333333;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.rule-btn-box {
    width: 100%;
    height: .4rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid #DCDFE6;
}

.rule-btn-box>div {
    flex: 1;
    flex-shrink: 0;
    height: 100%;
    color: #387BFF;
    border-right: 1px solid #DCDFE6;
    text-align: center;
    line-height: .4rem;
}

.rule-btn-box>div:last-child {
    border: none;
    color: #F84848;
}

.rule-form {
    width: 5rem;
    padding: 0.24rem;
    border-radius: 4px;
    background-color: #fff;
    overflow: hidden;
}
</style>
